<?php namespace framework\Model;

use Pdo;//声明底层空间的PDO类

/**
* 
*/
class Db
{
	// 声明表格变量
	public $table;
	// 声明pdo变量
	private $pdo;

	//声明一个方法数组
	private $option=[
		'where'=>'',
		'groupBy'=>'',
		'orderBy'=>'',
		'having'=>'',
		'limit'=>'',
	];

	//初始化构造函数里面的值
	public function __construct($table)
	{	
		$this->table = $table;
		
		$this->connect();
	}

	//链接数据库
	public function connect()
	{	
		// 连接数据源
		$dsn = 'mysql:host='.C('db_host').';dbname='.C('db_database');
		try {
			//创建连接对象
			$this->pdo = new Pdo($dsn,C('db_user'),C('db_password'));
			$this->pdo->query('set names utf8');
		} catch (PDOException $e) {
			die($e = getMessage());
			exit;
		}

	}

	// 查询
	public function query($sql,$params=[])
	{	
		// p($sql);
		p($params);
		// 预处理
		$sth = $this->pdo->prepare($sql);
		$id=0;
		//遍历参数
		foreach ($params as $p) {
			$id++;
			$vars ="hd{$id}";
			$$vars = $p;
			//绑定参数
			$sth->bindParam($id,$$vars,PDO::PARAM_STR);
		}
		//执行动作
		$sth->execute();
		//返回关联数组第一个
		return $sth->fetchAll(PDO::FETCH_ASSOC);
	}

	//执行增删改
	public function execute($sql,$params=[])
	{	
		//预处理
		$sth = $this->pdo->prepare($sql);
		// p($sth);
		$id=0;
		foreach ($params as $p) {
			$id++;
			$vars="hd{$id}";
			$$vars=$p;
			$sth->bindParam($id,$$vars, PDO::PARAM_STR);
			// $sth->bindParam($id, $$var, PDO::PARAM_STR);
		}
		//执行动作
		return $sth->execute();


	}

	//查找
	public function select()
	{	//select * from table where groupBy having orderBy limit;
		$sql=" SELECT * FROM " .$this->table. "{$this->option['where']} {$this->option['groupBy']} 
		{$this->option['having']} {$this->option['orderBy']} {$this->option['limit']}";

		return $this->query($sql);
	}

	public function where($arg)
	{
		$this->option['where'] = " WHERE $arg";
		return $this;
	}

	public function groupBy($arg)
	{
		$this->option['where'] = " groupBy $arg";
		return $this;
	}

	public function having($orderBy)
	{
		$this->option['having'] = " having $arg";
		return $this;
	}

	public function orderBy($arg)
	{
		$this->option['orderBy'] = " orderBy $arg";
		return $this;
	}

	public function limit($arg)
	{
		$this->option['limit'] = " limit $arg";
		return $this;
	}

}

 ?>